// c:\workspace\short-player-mini-app\pages\videoPlayer\videoPlayer.js
import {
  getPlayletEpisodeList,
  getPlayletDetail,
  getPlayletEpisodeDetail,
  togglePlayLike,
  addPlayLog
} from '../../api/modules/play';
import {
  VideoSwiper
} from '../../utils/video-swiper'
import {
  rpxToPx
} from '../../utils'
import {
  loginController
} from "../../utils/login"
import { orderPlayletUnlock } from '../../api/modules/trade';
import { ResultMessageEnum } from '../../config/resultMessageEnum';
import eventBus from '../../utils/eventBus';
import EventName from '../../config/eventName';
const app = getApp();
Page({
  data: {
    isFullScreen: false,
    currentAblum: {},
    allVideoData: [],
    isSlideStart: false,
    curQueue: [],
    swiperOptions: {
      circular: true, // 是否可以轮播，即尾部衔接头部
      duration: 500,
      current: 0,
    },
    showChangeVideoPopup: false,
    showUnlockDialog: false,
    currentVideo: null,
    // _currentVideo:null,//解锁用
    showFullScreenTool: false
  },
  onLoad: async function (options) {
    const {
      goodsId,
      eNum
    } = options;
    const {
      windowHeight,
      windowWidth
    } = app.globalData?.systemInfo;
    const {
      Hasbindgetsource = false
    } = app?.globalData;
    this.setData({
      windowHeight,
      windowWidth: Number(windowWidth) || rpxToPx(750),
      Hasbindgetsource,
    });
    await this.formatVideoData(goodsId, eNum);
    tt.disableUserScreenRecord();
    const videoSwiper = new VideoSwiper({
      swiperDuration: 500,
      start: this.data.start,
      total: this.data.allVideoData.length,
      getItem: (index) => {
        return this.data.allVideoData[index];
      },
      getVideo: async (index) => {
        let target = this.data.allVideoData[index];

        const {
          data
        } = await getPlayletEpisodeDetail(target.id);
        return {
          ...data,
          horizontal_screen: true,
          coverImage: data.coverImage || this.data.currentAblum.coverImage
        };
      },
      onSwiperOptionsChange: data => {
        this.setData({
          swiperOptions: {
            ...data,
          },
        });
      },
      onCurQueueChange: (data) => {
        this.setData({
          curQueue: [...data],
        });
      },
      onChangeEnd: () => {

        let _currentVideo = this.videoSwiper.getCurrentVideo();
        if (!_currentVideo) return;
        //TODO
        // this.videoSwiper.play()
        if (_currentVideo && _currentVideo.status === 'lock') {
          this.tryShowUnlockSelector()
        } else if (_currentVideo.status === 'success') {
          //this.videoSwiper.play()
        }
      },
      onVideoDestroy: videoInfo => {
        let episodeNum = videoInfo.episodeNum;
        let playInfo = this.data.playInfo;

        playInfo[episodeNum] = {};

        this.setData({
          playInfo: [...playInfo],
        });
      }
    })
    this.videoSwiper = videoSwiper;
  },
  slideStart(e) {
    this.setData({
      isSlideStart: true,
    });
  },
  // 全屏观看
  changeFullScreen(e) {
    let context = this.videoSwiper.getVideoContext();

    if (context) {
      context.play();
      context.requestFullScreen();
      this.setData({
        isFullScreen: true,
      });
    }
  },
  exitFullscreen(e) {
    this.videoSwiper.getVideoContext()?.exitFullScreen();
    this.setData({
      isFullScreen: false,
    });
  },
  fullScreenVideoPause(e) {
    const {
      isVideoPlay
    } = e.detail;
    this.videoSwiper.getVideoContext()?.[isVideoPlay ? 'pause' : 'play']();
  },
  videoPauseOrPlay(e) {
    const {
      videoPause
    } = e.detail;
    this.videoSwiper[videoPause ? 'play' : 'pause']();
  },
  // 进度条滑动结束事件
  slideEnd(e) {
    const {
      videoCurrentTimeSec
    } = e.detail;
    this.videoSwiper.getVideoContext()?.seek(videoCurrentTimeSec);
    this.setData({
      isSlideStart: false,
    });
  },
  async formatVideoData(goodsId, eNum = 1) {
    // 如果携带剧集id进来的话，需要计算他属于那个pageSize,
    const {
      data
    } = await getPlayletEpisodeList({
      goodsId: goodsId,
      pageSize: 999
    })

    const res = await getPlayletDetail(goodsId);
    const allVideoData = data.list || [];
    const currentIndex = allVideoData?.findIndex(i => i.episodeNum == eNum);
    // 当前剧信息
    const currentAblum = res.data;


    //playInfo用episodeNum做下标 episodeNum从1开始所以+1
    const playInfo = new Array(allVideoData.length + 1).map(v => {});

    this.setData({
      playInfo,
      allVideoData,
      currentAblum,
      start: currentIndex
    });

  },
  tryShowUnlockSelector() {
    let _currentVideo = this.videoSwiper.getCurrentVideo();
    if (!loginController.isDeveloperServerLogin()) {
      return
    }
    this.setData({
      currentVideo: _currentVideo,
      showUnlockDialog: true
    })
    //显示解锁弹窗
  },
  onShow() {
    tt.disableUserScreenRecord();
  },
  onHide() {
    tt.enableUserScreenRecord();
  },
  swiperChange: function (e) {
    this.videoSwiper.onchange(e);

    const {
      currentAblum
    } = this.data;

    let currentIndex = this.videoSwiper.currentIndex;
    let currentVideo = this.videoSwiper.getCurrentVideo();

    if (currentVideo) {
      // 隐藏暂停按钮
      this.selectComponent('#customSlider' + currentVideo.id, res => {
        res?.hidePauseIcon()
      });
    }
    // console.log(currentVideo)
    if (currentVideo) {
      tt.setNavigationBarTitle({
        title: `${currentAblum.title} 第${currentIndex+1}集`,
      });
    }

  },
  nextVideo() {},
  timeUpdateHandler(e) {
  
    const {
      currentTime,
      duration,
    } = e.detail;
    const {
      episode,
      goodsId
    } = e.target.dataset;
    let playInfo = this.data.playInfo;
    playInfo[episode].videoDuration = Math.floor(duration);
    playInfo[episode].videoCurrentTime = currentTime;
    addPlayLog({
      goodsId:goodsId,
      episodeNum:episode,
      playedTime:currentTime
    })
    this.setData({
      playInfo: [...playInfo],
    });
  },
  onTapVideo(e) {
    const {
      isFullScreen
    } = this.data;
    if (isFullScreen) {
      this.setData({
        showFullScreenTool: true,
      });
    }
  },
  // 选集
  onChangeEpisode(e) {
    const {
      episodeitem
    } = e.detail;
    let episode = episodeitem.episodeNum - 1;
    this.videoSwiper.setStart(episode);
    // 需要根据选中的信息确定swier滑到哪里
    this.setData({
      currentVideo: null,
      showChangeVideoPopup: false
    });
  },
  changeVideo(e) {
    let item = e.currentTarget.dataset.item;
    this.setData({
      currentVideo: item,
      showChangeVideoPopup: true,
    });
  },
  // 隐藏选集弹窗
  cancelChangeVideo() {
    this.setData({
      currentVideo: null,
      showChangeVideoPopup: false,
    });
  },
  showUnlockSelector() {
    this.setData({
      showUnlockDialog: true
    })
  },
  hideUnlockSelector() {
    this.setData({
      showUnlockDialog: false
    })
  },
  handleUnlockRetry(val) {
    // console.log(val)
    let _currentVideo = this.videoSwiper.getCurrentVideo();
    this.setData({
      currentVideo: _currentVideo,
      showUnlockDialog: true
    })
    // this.tryShowUnlockSelector()
  },
  async handleUnlockMethodSelected(val) {
    let _params = val.detail;
    try {
      await orderPlayletUnlock({previewCode:_params.previewCode,selectedSkuId:_params.skuId})
      this.videoSwiper.updateCurrentVideo();
      this.setData({
        showUnlockDialog:false
      })
    } catch (error) {
      if(error.toString()==ResultMessageEnum.BALANCE_INSUFFICIENT){
        tt.showModal({
          title:"提醒",
          content:"用户余额不足、是否前往充值",
          success: (res) => {
            if(res.confirm){
              tt.navigateTo({
                url: "/pages-mine/recharge/recharge"
              });
            }
          }
        });
      
      }else {
        console.log(error)
      }
    }
  },
  async likeHandler(e) {
    const {
      videoitem
    } = e.currentTarget.dataset;
  
    await togglePlayLike({
      goodsId: videoitem.goodsId,
      episodeNum: videoitem.episodeNum
    });
    eventBus.emit(EventName.LIKE_CHANGE,videoitem)

    // 重新获取当前 video 信息，更新点赞数量
    this.videoSwiper.updateCurrentVideo();
  },
})